package org.yjc.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.yjc.custom.JqgridParam;
import org.yjc.custom.JqgridUtils;
import org.yjc.entity.EndUser;
import org.yjc.entity.KingRoot;
import org.yjc.entity.Lessee;
import org.yjc.entity.LesseeAdmin;
import org.yjc.entity.Log;
import org.yjc.entity.SysRole;
import org.yjc.entity.SysUser;
import org.yjc.form.EndUserForm;
import org.yjc.repository.SysRoleRepository;
import org.yjc.repository.SysUserRepository;
import org.yjc.security.UserUtils;
import org.yjc.service.EndUserService;
import org.yjc.service.LesseeAdminService;
import org.yjc.service.LesseeService;
import org.yjc.service.LogService;

@Controller
@RequestMapping(value="/enduser")
public class EndUserController {
	@Autowired
	private EndUserService enduserservice;
	@Autowired
	private LesseeService lesseeservice;
	@Autowired
	private LesseeAdminService lesseeadminservice;
	@Autowired
	private SysRoleRepository sysroleDAO;
	@Autowired
	private UserUtils userutils;
	@Autowired
	SysUserRepository sysuserDAO;
	@Autowired
	private LogService logservice;
	
	@RequestMapping(value="/endusermain")
	public String alllessee(ModelMap map) {
		SysUser sysuser = new SysUser();
		//获取上下文对象
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String username = userDetails.getUsername();
		sysuser = lesseeadminservice.findByUsername(username);
		Integer id = sysuser.getId(); //获取到当前租户管理员的id
		List<Lessee> lessees = lesseeservice.findByLesseeadminId(id); //通过id查询该租户管理员的下级租户
		Integer lesseeid = 0;
		if(!lessees.isEmpty()) {
			lesseeid = lessees.get(0).getId();
		} //取每一个租户的id
		map.put("lessees",lessees);
		map.put("lesseeid",lesseeid);
		return "enduser/endusermain";
	}
	
	@RequestMapping(value="/enduserpwd")
	public String enduserpwd() {
		return "enduser/endchangepwd";
		
	}
	
	@RequestMapping(value="list")
	@ResponseBody
	public Object list(JqgridParam param,Integer lesseeId) {
		Pageable pageable = param.buildPageable();
		Specification spec = new Specification<KingRoot>() {

			@Override
			public Predicate toPredicate(Root<KingRoot> root, CriteriaQuery<?> arg1, CriteriaBuilder cb) {
				Predicate predicate = cb.equal(root.get("lessee").get("id"), lesseeId);
				return predicate;
			}
		};
		Page<EndUser> page;
		if(param.getSearch()) {
			spec = spec.and(param.buildSpec());
		}
		page = enduserservice.findAll(spec,pageable);
		return JqgridUtils.getPageResult(page);
	}
	
	@RequestMapping(value="/edit")
	@ResponseBody
	public Object edit (String id,EndUserForm form) {
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder(); //密码加密器
		String oper = form.getOper(); //url判断
		EndUser enduser = new EndUser(); 
		if("del".equals(oper)) {
			enduserservice.deleteById(Integer.parseInt(id));
		}else {
			if("edit".equals(oper)) {
				enduser = enduserservice.findById(Integer.parseInt(id));
			}
			BeanUtils.copyProperties(form, enduser,"id");
			enduser.setPassword(encoder.encode("111111")); //密码进行不可逆加密
			SysRole role = sysroleDAO.findById(3).get(); //添加权限
			enduser.getRoles().add(role);
			SysUser user = userutils.getUser();	 //获取当前用户
			Log log = new Log();
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
			log.setName(user.getUsername());
			log.setOperationTime(df.format(new Date())); //获取当前系统时间
			log.setOperatiobName("新增用户");
			logservice.save(log);
			enduserservice.save(enduser);
		}
		return "OK";
	}
	
	@RequestMapping(value="/changepwd")
	@ResponseBody
	public Object changepwd(Integer id,ModelMap map) {
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder(); //密码加密器
		EndUser enduser= enduserservice.findById(id);
		enduser.setPassword(encoder.encode("111111"));
		enduserservice.save(enduser);
		return "重置密码成功";
	}
	
	@RequestMapping(value="/pwd")
	@ResponseBody
	public Boolean pwd(String password) {
		String user = userutils.getUser().getPassword(); //获取该用户的密码
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder(); //密码加密器
		boolean f = encoder.matches(password,user); //比较密码是否一致
		return f;
	}
	


	@RequestMapping(value="/xg")
	public String enduserpwd(String pad) {
		SysUser user = userutils.getUser(); //获取到该用户
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
		user.setPassword(encoder.encode(pad)); //存入新密码
		sysuserDAO.save(user);
		return "redirect:../logout";
	}
}
